{%mainunit bitcoin_p2p.pas}

{$IFDEF INTERFACE}
type

  { TMsgBlock }

  TMsgBlock = class(TMsg)
    Version: DWord;
    PrevBlock: TSHA256Digest;
    MerkleRoot: TSHA256Digest;
    Timestamp: DWord;  // will work until year 2109 because its unsigned int
    Bits: DWord; // The calculated difficulty target being used for this block
    Nonce: DWord;
    TxCount: Integer; // number of transactions
    TxList: array of TMsgTx;
    destructor Destroy; override;
    procedure ParseAndProcess; override;
    function Serialize: String; override;
    class function GetCommand: Tp2pCommand; override;
  end;

{$ENDIF}
{$IFDEF IMPLEMENTATION}

destructor TMsgBlock.Destroy;
var
  I : Integer;
begin
  for I := 0 to TxCount-1 do
    TxList[I].Free;
  SetLength(TxList, 0);
  inherited Destroy;
end;

procedure TMsgBlock.ParseAndProcess;
var
  I   : Integer;
  Cnt : Integer;
begin
  {$warning this code is still untested}
  Version := ReadDWord;
  ReadBuffer(PrevBlock[1], Length(PrevBlock));
  ReadBuffer(MerkleRoot[1], Length(MerkleRoot));
  Timestamp := ReadDWord;
  Bits := ReadDWord;
  Nonce := ReadDWord;
  Cnt := ReadVarInt;
  SetLength(TxList, Cnt);
  TxCount := 0;
  for I := 0 to Cnt-1 do begin
    TxList[I] := TMsgTx.Create(FPeer, FReceiveData);
    Inc(TxCount);
    TxList[I].ParseAndProcess;
  end;
end;

function TMsgBlock.Serialize: String;
begin
  Result := ''; {$warning implement me}
end;

class function TMsgBlock.GetCommand: Tp2pCommand;
begin
  Result := 'block'#0#0#0#0#0#0#0;
end;

{$ENDIF}

